using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using KeyAuthService.Models;
using Microsoft.Extensions.Logging;

namespace KeyAuthService.Services
{
    /// <summary>
    /// KeyAuth核心服务
    /// </summary>
    public class KeyAuthService
    {
        private readonly ILogger<KeyAuthService> _logger;
        private readonly KeyAuthCore _keyAuthCore;
        private readonly KeyStorageService _keyStorageService;
        private readonly UIService _uiService;
        private readonly WebSocketServer _webSocketServer;
        private Dictionary<string, AppConnection> _authorizedConnections = new Dictionary<string, AppConnection>();

        public KeyAuthService(
            ILogger<KeyAuthService> logger,
            KeyAuthCore keyAuthCore,
            KeyStorageService keyStorageService,
            UIService uiService,
            WebSocketServer webSocketServer)
        {
            _logger = logger;
            _keyAuthCore = keyAuthCore;
            _keyStorageService = keyStorageService;
            _uiService = uiService;
            _webSocketServer = webSocketServer;
        }

        /// <summary>
        /// 处理WebSocket请求
        /// </summary>
        public WebSocketResponse HandleRequest(WebSocketRequest request)
        {
            try
            {
                // 根据action分发处理
                switch (request.Action)
                {
                    // 连接管理接口
                    case "Connect":
                        return HandleConnect(request);
                    case "Ping":
                        return HandlePing(request);
                    case "CloseConnection":
                        return HandleCloseConnection(request);
                    
                    // 密钥管理接口
                    case "GenerateKeyPair":
                        return HandleGenerateKeyPair(request);
                    case "ImportKey":
                        return WebSocketResponse.CreateError(request.RequestId, "access_denied", "ImportKey操作仅允许平台Service应用使用，不允许通过WebSocket访问");
                    case "ExportKey":
                        return WebSocketResponse.CreateError(request.RequestId, "access_denied", "ExportKey操作仅允许平台Service应用使用，不允许通过WebSocket访问");
                    case "DeleteKey":
                        return WebSocketResponse.CreateError(request.RequestId, "access_denied", "DeleteKey操作仅允许平台Service应用使用，不允许通过WebSocket访问");
                    case "ListKeys":
                        return HandleListKeys(request);
                    
                    // 权限认证接口
                    case "CreateSignedDID":
                        return HandleCreateSignedDID(request);
                    case "VerifyDID":
                        return HandleVerifyDID(request);
                    case "SignData":
                        return HandleSignData(request);
                    case "VerifyData":
                        return HandleVerifyData(request);
                    
                    // 配置管理接口
                    case "GetAuditLogs":
                        return HandleGetAuditLogs(request);
                    case "ReloadConfig":
                        return HandleReloadConfig(request);
                    
                    // 区块链合约接口
                    case "Invoke":
                        return HandleInvoke(request);
                    case "Query":
                        return HandleQuery(request);
                    
                    default:
                        return WebSocketResponse.CreateError(request.RequestId, "unknown_action", $"未知的操作: {request.Action}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理请求 {request.Action} 时发生异常");
                return WebSocketResponse.CreateError(request.RequestId, "internal_error", "内部服务器错误");
            }
        }

        /// <summary>
        /// 移除连接的授权
        /// </summary>
        public void RemoveConnectionAuthorization(string clientId)
        {
            try
            {
                // 从授权连接列表中移除
                if (_authorizedConnections.ContainsKey(clientId))
                {
                    var appConnection = _authorizedConnections[clientId];
                    _logger.LogInformation($"移除应用 {appConnection.AppInfo.app_name}（{appConnection.AppInfo.app_id}）的授权，连接ID: {clientId}");
                    _authorizedConnections.Remove(clientId);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"移除连接 {clientId} 的授权时发生异常");
            }
        }

        /// <summary>
        /// 获取授权连接字典
        /// </summary>
        /// <returns>授权连接字典</returns>
        public Dictionary<string, AppConnection> GetAuthorizedConnections()
        {
            return _authorizedConnections;
        }

        #region 连接管理接口

        /// <summary>
        /// 处理Connect请求
        /// </summary>
        private WebSocketResponse HandleConnect(WebSocketRequest request)
        {
            try
            {
                // 解析参数
                if (request.Params == null)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "参数不能为空");
                }

                var paramsJson = JsonSerializer.Serialize(request.Params);
                var connectParams = JsonSerializer.Deserialize<ConnectParams>(paramsJson);

                if (connectParams?.app_info == null)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少应用信息");
                }

                var appInfo = connectParams.app_info;
                
                // 验证必要信息
                if (string.IsNullOrEmpty(appInfo.app_name) || string.IsNullOrEmpty(appInfo.app_id))
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "应用名称和ID不能为空");
                }

                // 获取连接ID
                string connectionId = request.ClientId; // 从请求中获取WebSocket连接ID
                
                if (string.IsNullOrEmpty(connectionId))
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_client", "无法识别客户端连接");
                }
                
                // 弹出授权对话框
                var result = _uiService.ShowAppAuthorizationDialog(appInfo, connectParams.scopes);
                
                if (!result.IsAuthorized)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "user_rejected", "用户拒绝了连接请求");
                }
                
                // 记录已授权的连接
                var appConnection = new AppConnection
                {
                    ConnectionId = connectionId,
                    AppInfo = appInfo,
                    AuthorizedScopes = result.AuthorizedScopes,
                    AuthorizedKeys = result.AuthorizedKeys,
                    ConnectedAt = DateTime.Now,
                    ExpiresAt = result.SessionDurationMinutes < 0 ? 
                                DateTime.MaxValue : // 永不过期，与连接绑定
                                DateTime.Now.AddMinutes(result.SessionDurationMinutes)
                };
                
                _authorizedConnections[connectionId] = appConnection;
                
                // 更新连接使用的密钥信息
                string keyAddress = string.Empty;
                KeyInfo? authKey = null;
                
                if (result.AuthorizedKeys != null && result.AuthorizedKeys.Count > 0)
                {
                    authKey = result.AuthorizedKeys[0];
                    
                    // 获取密钥地址
                    if (!string.IsNullOrEmpty(authKey.PublicKey))
                    {
                        var (addresses, success) = _keyAuthCore.GetAddresses(authKey.PublicKey, authKey.Algorithm);
                        if (success && !string.IsNullOrEmpty(addresses))
                        {
                            try
                            {
                                // 解析地址JSON，格式如 {"eth":"0x123...","btc":"bc1..."}
                                var addressDict = JsonSerializer.Deserialize<Dictionary<string, string>>(addresses);
                                if (addressDict != null && addressDict.Count > 0)
                                {
                                    // 优先使用eth地址，如果没有则使用第一个地址
                                    if (addressDict.TryGetValue("eth", out var ethAddress))
                                    {
                                        keyAddress = ethAddress;
                                    }
                                    else
                                    {
                                        keyAddress = addressDict.First().Value;
                                    }
                                    
                                    // 更新密钥的地址信息
                                    authKey.Address = keyAddress;
                                    _keyStorageService.UpdateKey(authKey);
                                }
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(ex, "解析密钥地址失败");
                            }
                        }
                    }
                    
                    // 更新连接的密钥信息
                    _webSocketServer.UpdateConnectionAuthKey(connectionId, authKey.KeyName);
                    _webSocketServer.UpdateConnectionKeyAddress(connectionId, keyAddress);
                }
                
                _logger.LogInformation($"应用 {appInfo.app_name} 已获得授权，连接ID: {connectionId}");

                // 自动生成会话令牌
                string sessionToken = string.Empty;
                byte[]? sessionSignature = null;
                
                if (authKey != null)
                {
                    try
                    {
                        // 创建简单的随机会话令牌
                        string tokenId = Guid.NewGuid().ToString("N");
                        sessionToken = tokenId;
                        
                        // 创建完整的会话信息，但只在服务端存储，不直接返回给客户端
                        var sessionInfo = new SessionToken
                        {
                            TokenId = tokenId,
                            Issuer = appInfo.app_id,
                            Subject = authKey.KeyName,
                            KeyId = authKey.KeyName,
                            KeyAddress = keyAddress,
                            SessionInfo = new SessionInfo
                            {
                                ConnectionId = connectionId,
                                Scopes = result.AuthorizedScopes,
                                ClientInfo = new Dictionary<string, string>
                                {
                                    { "app_name", appInfo.app_name },
                                    { "app_version", appInfo.app_version ?? string.Empty },
                                    { "developer", appInfo.developer ?? string.Empty }
                                }
                            }
                        };
                        
                        // 设置有效期
                        sessionInfo.SetExpiry(result.SessionDurationMinutes);
                        
                        // 序列化为JSON并签名，验证令牌时使用
                        var sessionInfoJson = JsonSerializer.Serialize(sessionInfo);
                        
                        // 准备简单的头部
                        var headerObj = new Dictionary<string, string>
                        {
                            { "alg", authKey.Algorithm == "SM2" ? "SM2" : "ES256" },
                            { "typ", "SESSION" }
                        };
                        var headerJson = JsonSerializer.Serialize(headerObj);
                        
                        // 签名令牌 - 这个签名只用于验证令牌有效性，不需要发送给客户端
                        var (signature, signSuccess) = _keyAuthCore.SignData(authKey.PrivateKey, headerJson, sessionInfoJson);
                        if (signSuccess)
                        {
                            sessionSignature = signature;
                            
                            // 保存会话信息和签名到连接对象中
                            appConnection.SessionInfo = sessionInfo;
                            appConnection.SessionSignature = Convert.ToBase64String(signature);
                            appConnection.SessionData = sessionInfoJson;
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "生成会话令牌时发生异常");
                    }
                }

                // 返回连接结果
                return WebSocketResponse.Success(request.RequestId, new
                {
                    connection_id = connectionId,
                    authorized_scopes = result.AuthorizedScopes,
                    authorized_keys = result.AuthorizedKeys?.Select(k => new
                    {
                        key_name = k.KeyName,
                        algorithm = k.Algorithm,
                        public_key = k.PublicKey,
                        key_address = k.Address
                    }).ToList(),
                    session_token = !string.IsNullOrEmpty(sessionToken) ? sessionToken : null,
                    session_signature = sessionSignature != null ? Convert.ToBase64String(sessionSignature) : null
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理Connect请求时发生异常");
                return WebSocketResponse.CreateError(request.RequestId, "internal_error", "内部服务器错误");
            }
        }

        /// <summary>
        /// 处理Ping请求
        /// </summary>
        private WebSocketResponse HandlePing(WebSocketRequest request)
        {
            return WebSocketResponse.Success(request.RequestId, new { message = "Pong" });
        }

        /// <summary>
        /// 处理CloseConnection请求
        /// </summary>
        private WebSocketResponse HandleCloseConnection(WebSocketRequest request)
        {
            // 返回成功响应，WebSocketHandler将在发送响应后关闭连接
            return WebSocketResponse.Success(request.RequestId, new { message = "Connection will be closed" });
        }

        #endregion

        #region 密钥管理接口

        /// <summary>
        /// 处理GenerateKeyPair请求
        /// </summary>
        private WebSocketResponse HandleGenerateKeyPair(WebSocketRequest request)
        {
            try
            {
                // 解析参数
                if (request.Params == null)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "参数不能为空");
                }

                var paramsJson = JsonSerializer.Serialize(request.Params);
                var parameters = JsonSerializer.Deserialize<Dictionary<string, string>>(paramsJson);

                if (!parameters.TryGetValue("algo", out var algo) || string.IsNullOrEmpty(algo))
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少算法参数");
                }

                if (!parameters.TryGetValue("keyName", out var keyName) || string.IsNullOrEmpty(keyName))
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少密钥名称参数");
                }

                // 检查密钥名称是否已存在
                if (_keyStorageService.GetKey(keyName) != null)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "key_exists", $"密钥 {keyName} 已存在");
                }

                // 弹出确认对话框
                bool confirmed = _uiService.ShowConfirmDialog(
                    $"是否生成新的 {algo} 密钥对？\n\n名称: {keyName}",
                    "生成密钥对确认");

                if (!confirmed)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "user_cancelled", "用户取消了操作");
                }

                // 生成密钥对
                var (publicKey, privateKey, success) = _keyAuthCore.GenerateKeyPair(algo);
                if (!success)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "generate_failed", "生成密钥对失败");
                }

                // 创建密钥信息
                var keyInfo = new KeyInfo
                {
                    KeyName = keyName,
                    Algorithm = algo,
                    PublicKey = publicKey,
                    PrivateKey = privateKey,
                    CreatedAt = DateTime.Now
                };

                // 保存密钥
                if (!_keyStorageService.AddKey(keyInfo))
                {
                    return WebSocketResponse.CreateError(request.RequestId, "storage_failed", "保存密钥失败");
                }

                // 返回成功响应
                return WebSocketResponse.Success(request.RequestId, new { keyName, publicKey });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理GenerateKeyPair请求时发生异常");
                return WebSocketResponse.CreateError(request.RequestId, "internal_error", "内部服务器错误");
            }
        }

        /// <summary>
        /// 处理ListKeys请求
        /// </summary>
        private WebSocketResponse HandleListKeys(WebSocketRequest request)
        {
            try
            {
                // 获取所有密钥
                var keys = _keyStorageService.GetAllKeys();

                // 过滤敏感信息
                var keyList = keys.Select(k => new
                {
                    k.KeyName,
                    k.Algorithm,
                    k.PublicKey,
                    k.Address,
                    k.CreatedAt,
                    k.LastUsed,
                    k.Revoked,
                    k.RevokedAt
                }).ToList();

                // 返回成功响应
                return WebSocketResponse.Success(request.RequestId, keyList);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理ListKeys请求时发生异常");
                return WebSocketResponse.CreateError(request.RequestId, "internal_error", "内部服务器错误");
            }
        }

        #endregion

        #region 权限认证接口

        /// <summary>
        /// 处理CreateSignedDID请求
        /// </summary>
        private WebSocketResponse HandleCreateSignedDID(WebSocketRequest request)
        {
            try
            {
                // 解析参数
                if (request.Params == null)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "参数不能为空");
                }

                string connectionId = request.ClientId;
                if (string.IsNullOrEmpty(connectionId))
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_client", "无法识别客户端连接");

                // 检查连接是否已授权
                if (!_authorizedConnections.TryGetValue(connectionId, out var appConnection))
                    return WebSocketResponse.CreateError(request.RequestId, "unauthorized", "连接未经授权，请先调用Connect方法获取授权");

                // 检查是否有授权的密钥
                if (appConnection.AuthorizedKeys == null || appConnection.AuthorizedKeys.Count == 0)
                    return WebSocketResponse.CreateError(request.RequestId, "no_authorized_keys", "连接没有授权的密钥可用");

                // 使用第一个授权的密钥
                var keyInfo = appConnection.AuthorizedKeys[0];

                var paramsJson = JsonSerializer.Serialize(request.Params);
                var parameters = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(paramsJson);

                // 验证参数
                if (!parameters.TryGetValue("didInfo", out var didInfoElement) || didInfoElement.ValueKind != JsonValueKind.Object)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少DID信息或格式不正确");
                }
                string didInfo = didInfoElement.ToString();

                // 检查密钥是否已吊销
                if (keyInfo.Revoked)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "key_revoked", $"密钥 {keyInfo.KeyName} 已被吊销");
                }

                // 弹出确认对话框
                bool confirmed = _uiService.ShowConfirmDialog(
                    $"是否允许使用密钥 {keyInfo.KeyName} 签名DID文档？\n\nDID信息: {didInfo.Substring(0, Math.Min(200, didInfo.Length))}...",
                    "DID文档签名确认");

                if (!confirmed)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "user_cancelled", "用户取消了操作");
                }

                try
                {
                    // 解析DID信息
                    var didInfoJson = JsonDocument.Parse(didInfo).RootElement;
                    
                    // 获取密钥地址
                    string keyAddress = string.Empty;
                    
                    // 首先检查密钥是否已有地址
                    if (!string.IsNullOrEmpty(keyInfo.Address))
                    {
                        keyAddress = keyInfo.Address;
                    }
                    // 如果没有，尝试从连接信息中获取
                    else if (!string.IsNullOrEmpty(appConnection.ConnectionId))
                    {
                        keyAddress = _webSocketServer.GetConnectionKeyAddress(appConnection.ConnectionId) ?? string.Empty;
                    }
                    
                    // 如果仍然没有地址，则调用GetAddresses获取
                    if (string.IsNullOrEmpty(keyAddress))
                    {
                        var (addressesJson, addressSuccess) = _keyAuthCore.GetAddresses(keyInfo.PublicKey, keyInfo.Algorithm);
                        if (!addressSuccess) {
                            return WebSocketResponse.CreateError(request.RequestId, "address_error", "获取密钥地址失败");
                        }
                        
                        // 解析地址JSON，格式如 {"eth":"0x123...","btc":"bc1..."}
                        var addressDict = JsonSerializer.Deserialize<Dictionary<string, string>>(addressesJson);
                        if (addressDict != null && addressDict.Count > 0)
                        {
                            // 优先使用eth地址，如果没有则使用第一个地址
                            if (addressDict.TryGetValue("eth", out var ethAddress))
                            {
                                keyAddress = ethAddress;
                            }
                            else
                            {
                                keyAddress = addressDict.First().Value;
                            }
                            
                            // 更新密钥的地址信息
                            keyInfo.Address = keyAddress;
                            _keyStorageService.UpdateKey(keyInfo);
                            
                            // 更新连接的密钥地址信息
                            _webSocketServer.UpdateConnectionKeyAddress(appConnection.ConnectionId, keyAddress);
                        }
                        else
                        {
                            return WebSocketResponse.CreateError(request.RequestId, "invalid_address", "无法获取有效的密钥地址");
                        }
                    }
                    
                    // 使用密钥地址作为DID标识符
                    var didId = $"did:keyauth:{keyAddress}";

                    // 构建标准DID文档
                    var didDocument = new Dictionary<string, object>
                    {
                        ["@context"] = "https://www.w3.org/ns/did/v1",
                        ["id"] = didId,
                        ["created"] = DateTime.UtcNow.ToString("o"),
                        ["verificationMethod"] = new[]
                        {
                            new Dictionary<string, object>
                            {
                                ["id"] = $"{didId}#keys-1",
                                ["type"] = keyInfo.Algorithm == "SM2" ? "SM2VerificationKey2019" : "ECDSAVerificationKey2019",
                                ["controller"] = didId,
                                ["publicKeyPem"] = keyInfo.PublicKey
                            }
                        },
                        ["authentication"] = new[] { $"{didId}#keys-1" }
                    };

                    // 添加DID信息到文档
                    var didInfoDict = new Dictionary<string, object>();
                    foreach (var property in didInfoJson.EnumerateObject())
                    {
                        didInfoDict[property.Name] = property.Value.ValueKind switch
                        {
                            JsonValueKind.String => property.Value.GetString(),
                            JsonValueKind.Number => property.Value.GetDouble(),
                            JsonValueKind.True => true,
                            JsonValueKind.False => false,
                            _ => JsonSerializer.Deserialize<object>(property.Value.GetRawText())
                        };
                    }
                    
                    didDocument["didInfo"] = didInfoDict;

                    // 序列化DID文档
                    string didDocumentJson = JsonSerializer.Serialize(didDocument);

                    // 创建一个空的header，只包含算法信息
                    // 将ECDSA_P256算法转换为标准ES256
                    var header = new Dictionary<string, object>
                    {
                        ["alg"] = keyInfo.Algorithm == "ECDSA_P256" ? "ES256" : keyInfo.Algorithm
                    };
                    string headerJson = JsonSerializer.Serialize(header);

                    // 使用SignData签名
                    var (signature, signSuccess) = _keyAuthCore.SignData(keyInfo.PrivateKey, headerJson, didDocumentJson);
                    if (!signSuccess || signature == null || signature.Length == 0)
                    {
                        return WebSocketResponse.CreateError(request.RequestId, "sign_failed", "签名DID文档失败");
                    }

                    // 将签名添加到DID文档中
                    didDocument["proof"] = new Dictionary<string, object>
                    {
                        ["type"] = keyInfo.Algorithm == "SM2" ? "SM2Signature2019" : "EcdsaSecp256k1Signature2019",
                        ["created"] = DateTime.UtcNow.ToString("o"),
                        ["verificationMethod"] = $"{didId}#keys-1",
                        ["proofPurpose"] = "authentication",
                        ["signature"] = Convert.ToBase64String(signature)
                    };

                    // 更新密钥的最后使用时间
                    keyInfo.LastUsed = DateTime.Now;
                    _keyStorageService.UpdateKey(keyInfo);

                    // 返回签名的DID文档
                    return WebSocketResponse.Success(request.RequestId, new { 
                        didDocument = didDocument
                    });
                }
                catch (JsonException ex)
                {
                    _logger.LogError(ex, "解析或创建DID文档时发生JSON异常");
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_json", "无效的JSON格式");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理CreateSignedDID请求时发生异常");
                return WebSocketResponse.CreateError(request.RequestId, "internal_error", "内部服务器错误");
            }
        }

        /// <summary>
        /// 处理VerifyDID请求
        /// </summary>
        private WebSocketResponse HandleVerifyDID(WebSocketRequest request)
        {
            try
            {
                // 解析参数
                if (request.Params == null)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "参数不能为空");
                }

                var paramsJson = JsonSerializer.Serialize(request.Params);
                var parameters = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(paramsJson);

                if (!parameters.TryGetValue("didDocument", out var didDocumentElement) || 
                    (didDocumentElement.ValueKind != JsonValueKind.String && didDocumentElement.ValueKind != JsonValueKind.Object))
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少DID文档参数或格式不正确");
                }

                // 获取DID文档字符串
                string didDocument;
                if (didDocumentElement.ValueKind == JsonValueKind.String)
                {
                    // 如果是字符串，直接使用
                    didDocument = didDocumentElement.GetString() ?? string.Empty;
                }
                else
                {
                    // 如果是对象，序列化为字符串
                    didDocument = didDocumentElement.GetRawText();
                }

                if (string.IsNullOrEmpty(didDocument))
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "DID文档不能为空");
                }

                try
                {
                    // 解析DID文档
                    var didDocJson = JsonDocument.Parse(didDocument).RootElement;
                    
                    // 检查DID文档是否包含proof部分
                    if (!didDocJson.TryGetProperty("proof", out var proofElement) || 
                        proofElement.ValueKind != JsonValueKind.Object)
                    {
                        return WebSocketResponse.CreateError(request.RequestId, "invalid_did", "DID文档缺少proof部分");
                    }
                    
                    // 检查验证方法
                    if (!proofElement.TryGetProperty("verificationMethod", out var verificationMethodElement) || 
                        verificationMethodElement.ValueKind != JsonValueKind.String)
                    {
                        return WebSocketResponse.CreateError(request.RequestId, "invalid_did", "DID文档proof缺少verificationMethod");
                    }
                    
                    // 检查签名
                    if (!proofElement.TryGetProperty("signature", out var signatureElement) || 
                        signatureElement.ValueKind != JsonValueKind.String)
                    {
                        return WebSocketResponse.CreateError(request.RequestId, "invalid_did", "DID文档proof缺少signature");
                    }
                    
                    // 获取验证方法ID和签名
                    string verificationMethodId = verificationMethodElement.GetString() ?? string.Empty;
                    string signatureBase64 = signatureElement.GetString() ?? string.Empty;
                    
                    // 检查DID文档是否包含验证方法
                    if (!didDocJson.TryGetProperty("verificationMethod", out var methodsElement) || 
                        methodsElement.ValueKind != JsonValueKind.Array)
                    {
                        return WebSocketResponse.CreateError(request.RequestId, "invalid_did", "DID文档缺少verificationMethod数组");
                    }
                    
                    // 查找匹配的验证方法
                    string publicKeyPem = string.Empty;
                    foreach (var method in methodsElement.EnumerateArray())
                    {
                        if (method.TryGetProperty("id", out var idElement) && 
                            idElement.ValueKind == JsonValueKind.String &&
                            idElement.GetString() == verificationMethodId)
                        {
                            if (method.TryGetProperty("publicKeyPem", out var keyElement) && 
                                keyElement.ValueKind == JsonValueKind.String)
                            {
                                publicKeyPem = keyElement.GetString() ?? string.Empty;
                                break;
                            }
                        }
                    }
                    
                    if (string.IsNullOrEmpty(publicKeyPem))
                    {
                        return WebSocketResponse.CreateError(request.RequestId, "invalid_did", "无法找到匹配的验证方法公钥");
                    }
                    
                    // 创建不包含proof的DID文档副本用于验证
                    var didDocCopy = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(didDocument);
                    if (didDocCopy != null && didDocCopy.ContainsKey("proof"))
                    {
                        didDocCopy.Remove("proof");
                    }
                    
                    // 序列化不含proof的文档
                    string didDocWithoutProof = JsonSerializer.Serialize(didDocCopy);
                    
                    // 创建与签名时相同的header
                    var header = new Dictionary<string, object>
                    {
                        ["alg"] = didDocJson.TryGetProperty("verificationMethod", out var vmArray) && 
                                  vmArray.ValueKind == JsonValueKind.Array && 
                                  vmArray.GetArrayLength() > 0 && 
                                  vmArray[0].TryGetProperty("type", out var typeElement) && 
                                  typeElement.ValueKind == JsonValueKind.String && 
                                  typeElement.GetString()?.Contains("SM2") == true ? "SM2" : "ES256"
                    };
                    string headerJson = JsonSerializer.Serialize(header);
                    
                    // 解码签名
                    byte[] signature;
                    try
                    {
                        signature = Convert.FromBase64String(signatureBase64);
                    }
                    catch
                    {
                        return WebSocketResponse.CreateError(request.RequestId, "invalid_did", "签名格式无效");
                    }
                    
                    // 验证签名
                    bool isValid = _keyAuthCore.VerifyData(publicKeyPem, headerJson, didDocWithoutProof, signature);
                    
                    if (!isValid)
                    {
                        return WebSocketResponse.CreateError(request.RequestId, "invalid_did", "DID文档签名验证失败");
                    }
                    
                    // 返回验证结果和公钥
                return WebSocketResponse.Success(request.RequestId, new { 
                    valid = true,
                        publicKey = publicKeyPem
                    });
                }
                catch (JsonException ex)
                {
                    _logger.LogError(ex, "解析DID文档时发生JSON异常");
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_json", "无效的JSON格式");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理VerifyDID请求时发生异常");
                return WebSocketResponse.CreateError(request.RequestId, "internal_error", "内部服务器错误");
            }
        }





        /// <summary>
        /// 验证会话令牌
        /// </summary>
        /// <param name="token">会话令牌（简单随机字符串）</param>
        /// <returns>验证结果</returns>
        private (bool isValid, string errorMessage, object sessionInfo) VerifySessionToken(string token)
        {
            // 在授权连接列表中查找匹配的会话令牌
            foreach (var conn in _authorizedConnections.Values)
            {
                if (conn.SessionInfo?.TokenId == token)
                {
                    // 检查过期时间
                    if (conn.ExpiresAt < DateTime.Now)
                    {
                        return (false, "会话令牌已过期", null);
                    }
                    
                    // 创建包含部分信息的返回对象，不包括敏感数据
                    var sessionInfo = new
                    {
                        token_id = conn.SessionInfo.TokenId,
                        subject = conn.SessionInfo.Subject,
                        key_id = conn.SessionInfo.KeyId,
                        key_address = conn.SessionInfo.KeyAddress,
                        issued_at = conn.SessionInfo.IssuedAt,
                        expires_at = conn.SessionInfo.ExpiresAt,
                        scopes = conn.SessionInfo.SessionInfo.Scopes,
                        app_info = new
                        {
                            name = conn.AppInfo.app_name,
                            id = conn.AppInfo.app_id,
                            version = conn.AppInfo.app_version
                        }
                    };
                    
                    return (true, string.Empty, sessionInfo);
                }
            }
            
            return (false, "无效的会话令牌", null);
        }

        #endregion

        #region 配置管理接口

        /// <summary>
        /// 处理GetAuditLogs请求
        /// </summary>
        private WebSocketResponse HandleGetAuditLogs(WebSocketRequest request)
        {
            // TODO: 实现审计日志查询逻辑
            return WebSocketResponse.CreateError(request.RequestId, "not_implemented", "审计日志查询功能尚未实现");
        }

        /// <summary>
        /// 处理ReloadConfig请求
        /// </summary>
        private WebSocketResponse HandleReloadConfig(WebSocketRequest request)
        {
            // TODO: 实现配置重载逻辑
            return WebSocketResponse.CreateError(request.RequestId, "not_implemented", "配置重载功能尚未实现");
        }

        #endregion

        #region 区块链合约接口

        /// <summary>
        /// 处理Invoke请求 - 调用区块链合约方法
        /// </summary>
        private WebSocketResponse HandleInvoke(WebSocketRequest request)
        {
            try
            {
                // 解析参数
                if (request.Params == null)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "参数不能为空");
                }

                string connectionId = request.ClientId;
                if (string.IsNullOrEmpty(connectionId))
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_client", "无法识别客户端连接");

                // 检查连接是否已授权
                if (!_authorizedConnections.TryGetValue(connectionId, out var appConnection))
                    return WebSocketResponse.CreateError(request.RequestId, "unauthorized", "连接未经授权，请先调用Connect方法获取授权");

                // 检查是否有授权的密钥
                if (appConnection.AuthorizedKeys == null || appConnection.AuthorizedKeys.Count == 0)
                    return WebSocketResponse.CreateError(request.RequestId, "no_authorized_keys", "连接没有授权的密钥可用");

                // 检查是否有contract权限
                if (!appConnection.AuthorizedScopes.Contains("contract"))
                    return WebSocketResponse.CreateError(request.RequestId, "scope_denied", "连接未授权执行合约操作");

                // 使用第一个授权的密钥
                var keyInfo = appConnection.AuthorizedKeys[0];

                var paramsJson = JsonSerializer.Serialize(request.Params);
                var parameters = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(paramsJson);

                // 验证参数
                if (!parameters.TryGetValue("chainID", out var chainIDElement) || chainIDElement.ValueKind != JsonValueKind.String)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少链ID或格式不正确");
                }
                string chainID = chainIDElement.GetString() ?? string.Empty;

                if (!parameters.TryGetValue("nodeAddr", out var nodeAddrElement) || nodeAddrElement.ValueKind != JsonValueKind.String)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少节点地址或格式不正确");
                }
                string nodeAddr = nodeAddrElement.GetString() ?? string.Empty;

                if (!parameters.TryGetValue("nodePort", out var nodePortElement) || nodePortElement.ValueKind != JsonValueKind.Number)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少节点端口或格式不正确");
                }
                int nodePort = nodePortElement.GetInt32();

                if (!parameters.TryGetValue("contract", out var contractElement) || contractElement.ValueKind != JsonValueKind.String)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少合约名称或格式不正确");
                }
                string contract = contractElement.GetString() ?? string.Empty;

                if (!parameters.TryGetValue("method", out var methodElement) || methodElement.ValueKind != JsonValueKind.String)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少方法名称或格式不正确");
                }
                string method = methodElement.GetString() ?? string.Empty;

                // 获取参数，可选
                string paramsData = "{}";
                if (parameters.TryGetValue("params", out var paramsElement) && paramsElement.ValueKind == JsonValueKind.Object)
                {
                    paramsData = paramsElement.GetRawText();
                }

                // 检查密钥是否已吊销
                if (keyInfo.Revoked)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "key_revoked", $"密钥 {keyInfo.KeyName} 已被吊销");
                }

                // 构建调用信息
                string invokeInfo = $"链ID: {chainID}\n" +
                                   $"节点: {nodeAddr}:{nodePort}\n" +
                                   $"合约: {contract}\n" +
                                   $"方法: {method}\n" +
                                   $"参数: {paramsData}";

                // 弹出确认对话框
                bool confirmed = _uiService.ShowConfirmDialog(
                    $"是否允许使用密钥 {keyInfo.KeyName} 调用区块链合约？\n\n{invokeInfo}",
                    "区块链合约调用确认");

                if (!confirmed)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "user_cancelled", "用户取消了操作");
                }

                // 调用区块链合约
                var (resultJson, success) = _keyAuthCore.Invoke(chainID, nodeAddr, nodePort, contract, method, keyInfo.PrivateKey, paramsData);
                
                if (!success || string.IsNullOrEmpty(resultJson))
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invoke_failed", "调用合约失败");
                }

                // 更新密钥的最后使用时间
                keyInfo.LastUsed = DateTime.Now;
                _keyStorageService.UpdateKey(keyInfo);

                // 解析结果并返回
                try
                {
                    var resultObj = JsonSerializer.Deserialize<JsonElement>(resultJson);
                    return WebSocketResponse.Success(request.RequestId, resultObj);
                }
                catch (JsonException)
                {
                    // 如果无法解析为JSON，则返回原始字符串
                    return WebSocketResponse.Success(request.RequestId, new { result = resultJson });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理Invoke请求时发生异常");
                return WebSocketResponse.CreateError(request.RequestId, "internal_error", "内部服务器错误");
            }
        }

        /// <summary>
        /// 处理Query请求 - 查询区块链合约数据
        /// </summary>
        private WebSocketResponse HandleQuery(WebSocketRequest request)
        {
            try
            {
                // 解析参数
                if (request.Params == null)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "参数不能为空");
                }

                string connectionId = request.ClientId;
                if (string.IsNullOrEmpty(connectionId))
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_client", "无法识别客户端连接");

                // 检查连接是否已授权
                if (!_authorizedConnections.TryGetValue(connectionId, out var appConnection))
                    return WebSocketResponse.CreateError(request.RequestId, "unauthorized", "连接未经授权，请先调用Connect方法获取授权");

                // 检查是否有contract权限
                if (!appConnection.AuthorizedScopes.Contains("contract"))
                    return WebSocketResponse.CreateError(request.RequestId, "scope_denied", "连接未授权执行合约操作");

                // 使用第一个授权的密钥
                var keyInfo = appConnection.AuthorizedKeys[0];

                var paramsJson = JsonSerializer.Serialize(request.Params);
                var parameters = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(paramsJson);

                // 验证参数
                if (!parameters.TryGetValue("chainID", out var chainIDElement) || chainIDElement.ValueKind != JsonValueKind.String)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少链ID或格式不正确");
                }
                string chainID = chainIDElement.GetString() ?? string.Empty;

                if (!parameters.TryGetValue("nodeAddr", out var nodeAddrElement) || nodeAddrElement.ValueKind != JsonValueKind.String)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少节点地址或格式不正确");
                }
                string nodeAddr = nodeAddrElement.GetString() ?? string.Empty;

                if (!parameters.TryGetValue("nodePort", out var nodePortElement) || nodePortElement.ValueKind != JsonValueKind.Number)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少节点端口或格式不正确");
                }
                int nodePort = nodePortElement.GetInt32();

                if (!parameters.TryGetValue("contract", out var contractElement) || contractElement.ValueKind != JsonValueKind.String)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少合约名称或格式不正确");
                }
                string contract = contractElement.GetString() ?? string.Empty;

                if (!parameters.TryGetValue("method", out var methodElement) || methodElement.ValueKind != JsonValueKind.String)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少方法名称或格式不正确");
                }
                string method = methodElement.GetString() ?? string.Empty;

                // 获取参数，可选
                string paramsData = "{}";
                if (parameters.TryGetValue("params", out var paramsElement) && paramsElement.ValueKind == JsonValueKind.Object)
                {
                    paramsData = paramsElement.GetRawText();
                }

                // 查询区块链合约
                var (resultJson, success) = _keyAuthCore.Query(chainID, nodeAddr, nodePort, contract, method, keyInfo.PrivateKey, paramsData);
                
                if (!success || string.IsNullOrEmpty(resultJson))
                {
                    return WebSocketResponse.CreateError(request.RequestId, "query_failed", "查询合约失败");
                }

                // 解析结果并返回
                try
                {
                    var resultObj = JsonSerializer.Deserialize<JsonElement>(resultJson);
                    return WebSocketResponse.Success(request.RequestId, resultObj);
                }
                catch (JsonException)
                {
                    // 如果无法解析为JSON，则返回原始字符串
                    return WebSocketResponse.Success(request.RequestId, new { result = resultJson });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理Query请求时发生异常");
                return WebSocketResponse.CreateError(request.RequestId, "internal_error", "内部服务器错误");
            }
        }

        #endregion
        
        /// <summary>
        /// 处理SignData请求（新增）
        /// </summary>
        private WebSocketResponse HandleSignData(WebSocketRequest request)
        {
            try
            {
                // 解析参数
                if (request.Params == null)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "参数不能为空");
                }

                string connectionId = request.ClientId;
                if (string.IsNullOrEmpty(connectionId))
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_client", "无法识别客户端连接");

                // 检查连接是否已授权
                if (!_authorizedConnections.TryGetValue(connectionId, out var appConnection))
                    return WebSocketResponse.CreateError(request.RequestId, "unauthorized", "连接未经授权，请先调用Connect方法获取授权");

                // 检查是否有授权的密钥
                if (appConnection.AuthorizedKeys == null || appConnection.AuthorizedKeys.Count == 0)
                    return WebSocketResponse.CreateError(request.RequestId, "no_authorized_keys", "连接没有授权的密钥可用");

                // 使用第一个授权的密钥
                var keyInfo = appConnection.AuthorizedKeys[0];

                var paramsJson = JsonSerializer.Serialize(request.Params);
                var parameters = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(paramsJson);

                // 验证参数
                if (!parameters.TryGetValue("header", out var headerElement) || headerElement.ValueKind != JsonValueKind.Object)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少头部参数或格式不正确");
                }
                string headerJson = headerElement.ToString();

                if (!parameters.TryGetValue("payload", out var payloadElement) || payloadElement.ValueKind != JsonValueKind.Object)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少载荷参数或格式不正确");
                }
                string payloadJson = payloadElement.ToString();

                // 检查密钥是否已吊销
                if (keyInfo.Revoked)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "key_revoked", $"密钥 {keyInfo.KeyName} 已被吊销");
                }

                // 弹出确认对话框
                bool confirmed = _uiService.ShowConfirmDialog(
                    $"是否允许使用密钥 {keyInfo.KeyName} 签名数据？\n\n头部: {headerJson.Substring(0, Math.Min(100, headerJson.Length))}...\n\n载荷: {payloadJson.Substring(0, Math.Min(100, payloadJson.Length))}...",
                    "数据签名确认");

                if (!confirmed)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "user_cancelled", "用户取消了操作");
                }

                // 使用SignData进行签名
                var (signature, success) = _keyAuthCore.SignData(keyInfo.PrivateKey, headerJson, payloadJson);
                if (!success || signature.Length == 0)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "sign_failed", "签名失败");
                }

                // 更新密钥的最后使用时间
                keyInfo.LastUsed = DateTime.Now;
                _keyStorageService.UpdateKey(keyInfo);

                // 返回签名结果
                return WebSocketResponse.Success(request.RequestId, new { 
                    signature = Convert.ToBase64String(signature),
                    algorithm = keyInfo.Algorithm
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理SignData请求时发生异常");
                return WebSocketResponse.CreateError(request.RequestId, "internal_error", "内部服务器错误");
            }
        }
        
        /// <summary>
        /// 处理VerifyData请求（新增）
        /// </summary>
        private WebSocketResponse HandleVerifyData(WebSocketRequest request)
        {
            try
            {
                // 解析参数
                if (request.Params == null)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "参数不能为空");
                }

                var paramsJson = JsonSerializer.Serialize(request.Params);
                var parameters = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(paramsJson);

                // 验证参数
                if (!parameters.TryGetValue("header", out var headerElement) || headerElement.ValueKind != JsonValueKind.Object)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少头部参数或格式不正确");
                }
                string headerJson = headerElement.ToString();

                if (!parameters.TryGetValue("payload", out var payloadElement) || payloadElement.ValueKind != JsonValueKind.Object)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少载荷参数或格式不正确");
                }
                string payloadJson = payloadElement.ToString();

                if (!parameters.TryGetValue("signature", out var signatureElement) || signatureElement.ValueKind != JsonValueKind.String)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少签名参数或格式不正确");
                }
                string signatureBase64 = signatureElement.GetString() ?? string.Empty;

                // 公钥是必需的
                if (!parameters.TryGetValue("publicKey", out var publicKeyElement) || publicKeyElement.ValueKind != JsonValueKind.String)
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_params", "缺少公钥参数");
                }
                string publicKey = publicKeyElement.GetString() ?? string.Empty;

                // 解码签名
                byte[] signature;
                try
                {
                    signature = Convert.FromBase64String(signatureBase64);
                }
                catch
                {
                    return WebSocketResponse.CreateError(request.RequestId, "invalid_data", "签名参数不是有效的Base64");
                }

                // 使用VerifyData验证
                bool isValid = _keyAuthCore.VerifyData(publicKey, headerJson, payloadJson, signature);

                return WebSocketResponse.Success(request.RequestId, new { valid = isValid });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理VerifyData请求时发生异常");
                return WebSocketResponse.CreateError(request.RequestId, "internal_error", "内部服务器错误");
            }
        }
        


        #region 辅助方法

        /// <summary>
        /// Base64Url编码
        /// </summary>
        private string Base64UrlEncode(byte[] data)
        {
            string base64 = Convert.ToBase64String(data);
            // 转换为URL安全格式：替换+为-，/为_，去掉=
            return base64.Replace('+', '-').Replace('/', '_').TrimEnd('=');
        }

        /// <summary>
        /// Base64Url解码
        /// </summary>
        private byte[] Base64UrlDecode(string encoded)
        {
            // 添加必要的填充
            string padding = string.Empty;
            int padNeeded = encoded.Length % 4;
            if (padNeeded > 0)
                padding = new string('=', 4 - padNeeded);

            // 恢复为标准Base64格式
            string base64 = encoded.Replace('-', '+').Replace('_', '/') + padding;
            
            // 解码
            return Convert.FromBase64String(base64);
        }
        
        /// <summary>
        /// 从JWT中提取payload部分并解码
        /// </summary>
        private string ExtractPayloadFromJWT(string jwt)
        {
            try
            {
                // JWT格式: header.payload.signature
                string[] parts = jwt.Split('.');
                if (parts.Length != 3)
                {
                    return string.Empty;
                }
                
                // 解码payload
                var payloadBytes = Base64UrlDecode(parts[1]);
                return System.Text.Encoding.UTF8.GetString(payloadBytes);
            }
            catch
            {
                return string.Empty;
            }
        }

        #endregion
    }

    /// <summary>
    /// 应用连接信息
    /// </summary>
    public class AppConnection
    {
        /// <summary>
        /// 连接ID
        /// </summary>
        public string ConnectionId { get; set; } = string.Empty;
        
        /// <summary>
        /// 应用信息
        /// </summary>
        public AppInfo AppInfo { get; set; } = new AppInfo();
        
        /// <summary>
        /// 授权的权限范围
        /// </summary>
        public List<string> AuthorizedScopes { get; set; } = new List<string>();
        
        /// <summary>
        /// 授权的密钥
        /// </summary>
        public List<KeyInfo> AuthorizedKeys { get; set; } = new List<KeyInfo>();
        
        /// <summary>
        /// 连接时间
        /// </summary>
        public DateTime ConnectedAt { get; set; }
        
        /// <summary>
        /// 过期时间
        /// </summary>
        public DateTime ExpiresAt { get; set; }
        
        /// <summary>
        /// 会话信息（完整会话对象）
        /// </summary>
        public SessionToken SessionInfo { get; set; } = new SessionToken();
        
        /// <summary>
        /// 会话签名（Base64格式）
        /// </summary>
        public string SessionSignature { get; set; } = string.Empty;
        
        /// <summary>
        /// 会话数据（JSON格式）
        /// </summary>
        public string SessionData { get; set; } = string.Empty;
    }

    /// <summary>
    /// Connect请求参数
    /// </summary>
    public class ConnectParams
    {
        /// <summary>
        /// 应用信息
        /// </summary>
        public AppInfo app_info { get; set; } = new AppInfo();
        
        /// <summary>
        /// 请求的权限范围
        /// </summary>
        public List<string> scopes { get; set; } = new List<string>();
    }

    /// <summary>
    /// 应用信息
    /// </summary>
    public class AppInfo
    {
        /// <summary>
        /// 应用名称
        /// </summary>
        public string app_name { get; set; } = string.Empty;
        
        /// <summary>
        /// 应用ID
        /// </summary>
        public string app_id { get; set; } = string.Empty;
        
        /// <summary>
        /// 应用版本
        /// </summary>
        public string app_version { get; set; } = string.Empty;
        
        /// <summary>
        /// 开发者
        /// </summary>
        public string developer { get; set; } = string.Empty;
        
        /// <summary>
        /// 图标URL
        /// </summary>
        public string icon_url { get; set; } = string.Empty;
        
        /// <summary>
        /// 描述
        /// </summary>
        public string description { get; set; } = string.Empty;
    }

    /// <summary>
    /// 应用授权结果
    /// </summary>
    public class AppAuthorizationResult
    {
        /// <summary>
        /// 是否授权
        /// </summary>
        public bool IsAuthorized { get; set; }
        
        /// <summary>
        /// 授权的权限范围
        /// </summary>
        public List<string> AuthorizedScopes { get; set; } = new List<string>();
        
        /// <summary>
        /// 授权的密钥
        /// </summary>
        public List<KeyInfo> AuthorizedKeys { get; set; } = new List<KeyInfo>();
        
        /// <summary>
        /// 会话持续时间（分钟）
        /// </summary>
        public int SessionDurationMinutes { get; set; } = 30;
    }
} 